﻿using System;
using System.Text;
using XcoAppSpaces.Transport.Sockets.Auth.Contract.DoClientHandshake;
using XcoAppSpaces.Transport.Sockets.Auth.Contract;
#if SILVERLIGHT
using System.Net.Sockets;
#endif

namespace XcoAppSpaces.Transport.Sockets.Auth
{
	class SendGreeting : ISendGreeting
	{
		private byte[] greetingBytes;

		public void In_Connection(ConnectionInfo conn)
		{
			//Console.WriteLine("SendGreeting.In_Connection");
#if !SILVERLIGHT

			try
			{
				conn.Stream.Write(greetingBytes, 0, greetingBytes.Length);
				Out_ValidConnection(conn);
			}
			catch
			{
				Out_InvalidConnection(conn.Client);
			}
#else
			conn.Client.Socket.Send(greetingBytes, (s, e) =>
				{
					if (e.SocketError == SocketError.Success)
						Out_ValidConnection(conn);
					else
						Out_InvalidConnection(conn.Client);
				});
#endif
		}

		public event ValidConnectionHandler Out_ValidConnection;

		public event TcpClientHandler Out_InvalidConnection;

		public void Inject(SecuritySettings securitySettings)
		{
			greetingBytes = Encoding.UTF8.GetBytes(securitySettings.Greeting);
		}
	}
}